package com.example.tangyee.activity;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.tangyee.R;
import com.example.tangyee.fragment.SearchResultFragment;
import com.example.tangyee.utils.ConstantsUtil;
import com.example.tangyee.utils.SessionidUtils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class SearchActivity extends AppCompatActivity {

    private static final String TAG = "SearchActivity";

    private Unbinder mUnbinder;

    @BindView(R.id.root_view)
    View rootView;

    @BindView(R.id.searchView)
    SearchView mSearchView;
    @BindView(R.id.hot1)
    TextView hot1;
    @BindView(R.id.hot2)
    TextView hot2;
    @BindView(R.id.hot3)
    TextView hot3;
    @BindView(R.id.hot4)
    TextView hot4;
    @BindView(R.id.hot5)
    TextView hot5;

    @BindView(R.id.tabLayout)
    TabLayout mTabLayout;
    @BindView(R.id.viewPager)
    ViewPager mViewPager;

    @BindView(R.id.search_result_view)
    LinearLayout searchResultView;
    @BindView(R.id.hotView)
    LinearLayout hotView;

    List<SearchResultFragment> fragments = new ArrayList<>();
    List<String> titles = new ArrayList<>();

    private GetHotSearch mGetHotSearch;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_layout);
        mUnbinder = ButterKnife.bind(this);
        // 初始化视图
        initViews();

        mGetHotSearch = new GetHotSearch();
        mGetHotSearch.execute();
    }

    private void initViews() {
        //设置是否显示搜索框展开时的提交按钮
        mSearchView.setSubmitButtonEnabled(true);
        //设置输入框提示语
        mSearchView.setQueryHint("搜索");
        //设置搜索框直接展开显示。左侧有无放大镜(在搜索框中) 右侧无叉叉 有输入内容后有叉叉 不能关闭搜索框
        mSearchView.onActionViewExpanded();
        mSearchView.setIconifiedByDefault(false);//默认为true在框内，设置false则在框外
        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                doQuery(s);
                mSearchView.clearFocus();
                return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                return false;
            }
        });

        titles.add("健康知识");
        titles.add("常用食谱");
        titles.add("健康视频");

    }

    private void doQuery(String s) {
        fragments.clear();
        fragments.add(SearchResultFragment.newInstance(s, "know"));
        fragments.add(SearchResultFragment.newInstance(s, "recipe"));
        fragments.add(SearchResultFragment.newInstance(s, "video"));
        // 初始化ViewPager，并设置Adapter
        mViewPager.setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int i) {
                return fragments.get(i);
            }

            @Override
            public int getCount() {
                return fragments.size();
            }

            @Nullable
            @Override
            public CharSequence getPageTitle(int position) {
                return titles.get(position);
            }
        });
        // 将 TabLayout 与 ViewPager 关联起来
        mTabLayout.setupWithViewPager(mViewPager);
        mViewPager.setOffscreenPageLimit(2);

        hotView.setVisibility(View.GONE);
        searchResultView.setVisibility(View.VISIBLE);
    }

    @OnClick({R.id.hot1, R.id.hot2, R.id.hot3, R.id.hot4, R.id.hot5})
    void hotClcked(View view) {
        switch (view.getId()) {
            case R.id.hot1:
                mSearchView.setQuery(((TextView) view).getText().toString(), true);
                break;
            case R.id.hot2:
                mSearchView.setQuery(((TextView) view).getText().toString(), true);
                break;
            case R.id.hot3:
                mSearchView.setQuery(((TextView) view).getText().toString(), true);
                break;
            case R.id.hot4:
                mSearchView.setQuery(((TextView) view).getText().toString(), true);
                break;
            case R.id.hot5:
                mSearchView.setQuery(((TextView) view).getText().toString(), true);
                break;
        }
    }

    private class GetHotSearch extends AsyncTask<Void, Void, List<String>> {

        @Override
        protected List<String> doInBackground(Void... voids) {
            List<String> strings = new ArrayList<>();
            if (isCancelled()) {
                return strings;
            }
            try {
                SessionidUtils.updateSessionId(SearchActivity.this);
                Document document = Jsoup.connect(ConstantsUtil.SEARCH).cookie("ASP.NET_SessionId", SessionidUtils.getSessionId(SearchActivity.this)).get();
                Elements lis = document.select("ul>li");
                for (Element li : lis) {
                    strings.add(li.text());
                }
            } catch (SocketTimeoutException ste) {
                Log.e(TAG, "doInBackground: ", ste);
                return null;
            } catch (IOException e) {
                Log.e(TAG, "doInBackground: ", e);
                return null;
            }
            return strings;
        }

        @Override
        protected void onPostExecute(List<String> list) {
            if (list == null) {
                Snackbar.make(rootView, "网络异常,获取热门搜索失败.", Snackbar.LENGTH_SHORT).show();
                return;
            }
            Log.d(TAG, "onPostExecute: " + list.size());
            TextView[] views = new TextView[]{hot1, hot2, hot3, hot4, hot5};
            for (int i = 0; i < list.size() && i < views.length; i ++) {
                views[i].setText(list.get(i));
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mGetHotSearch != null) {
            mGetHotSearch.cancel(true);
        }
        if (mUnbinder != null) {
            mUnbinder.unbind();
        }
    }
}
